/** 账号服务 */
import { Inject, Provide } from '@midwayjs/core';
import { IAccountOption, IRegisterOption, IResultObject } from './interface';
import { Context } from '@midwayjs/koa';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Account } from '../../entity/account.entity';
import { Repository } from 'typeorm';
import { v4 as uuid } from 'uuid';

@Provide()
export class AccountService {

  @Inject()
  ctx: Context;

  @InjectEntityModel(Account)
  entityModel: Repository<Account>
  
  /** 登录 */
  async login(option: IAccountOption ): Promise<IResultObject> {
    const { username, password } = option;
    const result = await this.entityModel.findOne({
      where: {
        username,
        password
      }
    })
    if(result){
      
      return {
        success: true,
        msg: "登录成功",
        data: {
          username: result.username,
          identity: result.identity
        },
      }
    } else {
      return {
        success: false,
        msg: "登录失败"
      }
    }
  }

  /** 注册 */
  async register(option: IRegisterOption): Promise<{
    msg: string;
    success: boolean;
    data?: object;
  }> {
    const { identity, username, password } = option;
    const acc = await this.entityModel.findOne({
      where: {
        username
      }
    });
    if(acc) {
      return {
        msg: 'username 已被注册',
        success: false
      }
    }
    const account = new Account();
    account.uuid = uuid();
    account.identity = identity;
    account.username = username;
    account.password = password;
    const accountObject = await this.entityModel.save(account);
    return {
      msg: '创建成功',
      success: true,
      data: accountObject,
    }
  }

  async getAllUsers(): Promise<Array<any>> {
    const users = this.entityModel.find();
    return users;
  }
}
